package com.example.utils;

import io.jsonwebtoken.*;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <h3>duty-test1</h3>
 * <p></p>
 *
 * @author : 你的名字
 * @date : 2020-03-20 16:21
 **/
@Getter
@Setter
@ConfigurationProperties(prefix = "jwt.config")
@Component
public class JwtUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtUtils.class);
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";

    private String secret;
    private Long expiration;
    private String tokenHead;

    /**
     * 设置认证token
     *      id：登录用户id
     *      subject：登陆用户名
     */
    public String create(Map<String, Object> map) {
        //1.设置失效时间
        long now = System.currentTimeMillis(); //当前毫秒
        long exp = now + expiration*1000;
        //2.创建jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder()
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS512, secret); //密码太简单会报错
        //3.根据map设置claims
        jwtBuilder.setClaims(map);
        //4.设置失效时间
        jwtBuilder.setExpiration(new Date(exp));
        //5.创建token
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 根据用户信息生成token
     */
    public String create(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return create(claims);
    }

    /**
     * 解析token字符串获取clamis
     */
    public Claims parse(String token) {
        //私有数据存放在Claim中
        Claims claim = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claim;
    }
}
